package com.dream.libxrec.encode.audio;

import android.content.Context;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.os.Bundle;

public class AACEncoder extends IAudioMediaCodecEncoder {

    public static final String KEY_EXTRA_AAC_PROFILE_LEVEL =
            MediaFormat.KEY_AAC_PROFILE;
    public static final int AAC_PROFILE_LEVEL_LC =
            MediaCodecInfo.CodecProfileLevel.AACObjectLC;
    public static final int AAC_PROFILE_LEVEL_HE =
            MediaCodecInfo.CodecProfileLevel.AACObjectHE;
    public static final int AAC_PROFILE_LEVEL_HE_PS =
            MediaCodecInfo.CodecProfileLevel.AACObjectHE_PS;

    public static final int AAC_PROFILE_LEVEL_MAIN =
            MediaCodecInfo.CodecProfileLevel.AACObjectMain;


    /**
     *
     * @param sampleRate 采样率
     * @param codecBitRate 码率 8000 ~ 441000
     * @param channelNum 通道数（1或2）
     * @param extra :
     *      KEY:KEY_EXTRA_AAC_PROFILE_LEVEL
     *      VALUE:
     *           AAC_PROFILE_LEVEL_LC(大部分终端都支持)
     *           AAC_PROFILE_LEVEL_MAIN
     *           AAC_PROFILE_LEVEL_HE
     *           AAC_PROFILE_LEVEL_HE_PS
     *
     */
    public IAudioEncoder init(Context ct, int sampleRate, int codecBitRate,
                      int channelNum, Bundle extra){

        int profileLevel = extra.getInt(KEY_EXTRA_AAC_PROFILE_LEVEL,
                AAC_PROFILE_LEVEL_LC);
        init(ct, sampleRate, codecBitRate, channelNum,profileLevel);
        return this;
    }

    /**
     *
     *
     * @param ct
     * @param sampleRate PCM数据的采样率
     * @param codecBitRate 编码码率，码率越大则音质越好，音频文件也越大
     * @param channelNum 通道数（1或2）
     * @param profileLevel
     *           AAC_PROFILE_LEVEL_LC(大部分终端都支持)
     *           AAC_PROFILE_LEVEL_MAIN
     *           AAC_PROFILE_LEVEL_HE
     *           AAC_PROFILE_LEVEL_HE_PS
     * @return
     */
    public IAudioEncoder init(Context ct, int sampleRate, int codecBitRate,
                        int channelNum,int profileLevel){

        mEncoderFormat =
                MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, sampleRate, channelNum);
        mEncoderFormat.setInteger(MediaFormat.KEY_BIT_RATE, codecBitRate);
        //编码的码率，和解码时的比特率不一样,码率越大则文件越大，
        mEncoderFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, profileLevel);
        mEncoderFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 4096);
        //编码的码率，和解码时的比特率不一样,码率越大则文件越大，
        mEncoderFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, profileLevel);

        try {
            mEncoder = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this;
    }
}